package com.niit.controller;

import com.niit.entity.User;
import com.niit.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class LoginController {

    @Resource
    private UserMapper userMapper;



    @PostMapping("/login")
    public User login(@RequestBody User user, HttpServletRequest request, HttpSession session){
        //前端发送的数据
        System.out.println("前端发送的数据:"+user);
        //从数据库获取数据
        User dbuser = this.userMapper.findByUsername(user.getUsername());
        System.out.println("数据库查询到的信息:"+dbuser);
        if (user.getPassword().equals(dbuser.getPassword())){
                //验证成功，记录Session信息
                String username = user.getUsername();
                request.getSession().setAttribute("userName", username);
                request.getSession().setAttribute("userId", dbuser.getId());
                System.out.println("Session信息:"+request.getSession().getAttribute("userName"));
                System.out.println("密码正确！"+dbuser.getId());
                session.setAttribute("userID",dbuser.getId());
                System.out.println("Session信息:"+session.getAttribute("userID"));
                System.out.println("Session信息:"+request.getSession().getAttribute("userId"));
                System.out.println("密码正确！");
                return dbuser;
        }
        System.out.println("密码错误！");
        return user;
    }
    @PostMapping("/register")
    public User register(@RequestBody User user){
        System.out.println("注册信息:"+user);
        String username = user.getUsername();
        String password = user.getPassword();
        String email = user.getEmail();
        int roleId = user.getRoleId();
        if (userMapper.findByUsername(username)!=null) {
            System.out.println("已经注册过了！请重新注册！");
            return user; // 返回注册页面并提示错误信息
        } else {
            // 如果验证通过，将用户信息保存到数据库中
            User dbuser = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setRoleId(roleId);
            userMapper.insert(user);
            System.out.println("注册成功！"+user);
            return user; // 跳转到注册成功页面
        }
    }


    }

